import React, { Component } from 'react';
import {
  StyleSheet, View, Text, Dimensions, FlatList, TouchableOpacity, Image, ActivityIndicator, Alert,
} from 'react-native';
import PropTypes from 'prop-types';
import SearchBox from '../../utils/SearchBox';
import CustomErrorView from '../../utils/CustomErrorView';
import CustomLoadingView from '../../utils/CustomLoadingView';
import myStyles from '../../utils/myStyles';
import ClientUtil from '../../utils/ClientUtil';
import HTTPUtil from '../../utils/HTTPUtil';
import handleData from './handleData';

const GET_PROJECT_LIST = `${ClientUtil.HOST}/bff/employeeDailyReport/getProjectsForReport/`;
const GET_PROJECT_DETAIL = `${ClientUtil.HOST}/bff/employeeDailyReport/getPackageStaffForReport/`;
let isLoadMore = false;

class ProjectList extends Component {
  static propTypes = {
    headers: PropTypes.object,
    hasedProList: PropTypes.array,
    onClose: PropTypes.func,
  };

  constructor(props) {
    super(props);
    this.state = {
      errorMsg: '',
      isLoading: true,
      pageNo: 1, // 当前页, 0表示 所有页都加载完成
      searchTxt: '', // 搜索文本
      projectCodeList: [],
      projectList: [], // 项目列表
    };
  }

  componentDidMount() {
    isLoadMore = false;
    this.getList();
  }

  getList() {
    console.log('getList pageNo:', this.state.pageNo);
    const that = this;
    let {
      pageNo, searchTxt, projectList, projectCodeList,
    } = this.state;
    let postData = { 
      packageStaffForReportDto: {
        projectName: searchTxt
      }
    };
    HTTPUtil.postHasToken(`${GET_PROJECT_LIST}?pageNo=${pageNo}`, this.props.headers, postData).then((response) => {
      console.log('getProjectList response:', response);
      isLoadMore = false;
      if (response.result && response.result.records) {
        let res = response.result;
        if (pageNo === 1 && searchTxt) { // 模糊搜索
          projectList = [];
          projectCodeList = [];
        }
        if (res.pages > pageNo) {
          that.setState((state) => ({ pageNo: state.pageNo + 1 }));
        } else {
          that.setState({ pageNo: 0 });
        }
        if (res.records.length) {
          res.records.forEach((item) => {
            if (item.projectCode && !projectCodeList.includes(item.projectCode)) {
              projectCodeList.push(item.projectCode);
              projectList.push({
                projectCode: item.projectCode,
                projectName: item.projectName,
                projectId: item.projectId,
                stageCode:'',
                stageName:'',
                check: false,
                gsTotalHour: 0,
                gsTotalMinute: 0,
                workPackages: [],
              });
            }
          });
          console.log('getProjectList projectList1:', projectList);
          if (that.props.hasedProList.length) {
            console.log('getProjectList that.props.hasedProList:', that.props.hasedProList);
            projectList = handleData.projectAddGs(that.props.hasedProList,projectCodeList,projectList);
            console.log('getProjectList projectList 2:', projectList);
          }
          that.setState({
            projectList, projectCodeList, isLoading: false, errorMsg: '',
          });
        } else if (that.props.hasedProList.length) {
          console.log('getProjectList 接口没有返回项目:', res);
          projectList = that.props.hasedProList;
          that.setState({ projectList, isLoading: false, errorMsg: '' });
        } else {
          console.log('getProjectList 接口没有返回项目:', res);
          that.setState({ isLoading: false, errorMsg: '项目列表为空！' });
        }
      } else {
        console.log('getProjectList 数据格式有误:', res);
        that.setState({ isLoading: false, errorMsg: '获取项目失败，数据格式有误！' });
      }
    }).catch((error) => {
      console.log('getprojectList error:', error);
      that.setState({ isLoading: false, errorMsg: '获取项目失败，请检查网络后重试！' });
    });
  }

  // 上拉加载更多数据
  loadMoreData = () => {
    console.log('loadMoreData 上拉加载更多数据');
    if (this.state.pageNo && !isLoadMore) {
      isLoadMore = true;
      this.getList();
    }
  }


  onProjectSelected = (idx) => {
    // console.log('onProjectSelected idx:', idx);
    const { projectList } = this.state;
    projectList[idx].checked = !projectList[idx].checked;
    this.setState({ projectList });
  }

  onProjectSureClick = () => {
    // console.log('onProjectSureClick');
    const that = this;
    if (that.state.errorMsg) {
      that.props.onClose();
      return;
    }
    let projectList = [],projectCodes = [];
    that.state.projectList.forEach((item) => {
      if(item.checked){
        projectList.push(item);
        projectCodes.push(item.projectCode);
      }
    });
    // let notSelectedlist = that.state.projectList.filter((item) => !item.checked);
    if (projectList.length) {
      console.log('onProjectSureClick list:', projectList);
      HTTPUtil.postHasToken(GET_PROJECT_DETAIL, this.props.headers,projectCodes.join(',')).then((res) => {
        console.log('onProjectSureClick res:', res);
        if(res && res.result && res.result.length){
          let list = handleData.formatDbToCollapseList(res.result, null);//不含带过来的工时
          console.log('onProjectSureClick list1:', list);
          list = handleData.projectAddGs(projectList,projectCodes,list);
          that.props.onClose(list);
        }else{
          console.log('onProjectSureClick 项目详情为空 res:', res);
          Alert.alert('提示', '获取项目详情为空！', { cancelable: false });
        }
      }).catch((error) => {
        console.log('onProjectSureClick error:', error);
        Alert.alert('提示', '获取项目详情失败，请检查网络后重试！', { cancelable: false });
      });
      // that.props.onClose(list);
    } else {
      Alert.alert(
        '提示',
        '您未选中任何项目！',
        [
          { text: '取消', style: 'cancel' },
          {
            text: '确定',
            onPress: () => that.props.onClose(null, true),
          },
        ],
        { cancelable: false },
      );
    }
  }

  renderRow({ item, index }) {
    return (
      <TouchableOpacity key={item.projectId} onPress={() => this.onProjectSelected(index)}>
        <View style={[styles.listItem, myStyles.flexRowSpaceBetween]}>
          <View style={[styles.projectInfo, myStyles.lineBorderBottom]}>
            <Text style={[styles.projectText, item.checked && styles.checkedText]} numberOfLines={1}>{item.projectCode}</Text>
            <Text style={[styles.projectText, { marginTop: 8 }, item.checked && styles.checkedText]} numberOfLines={1}>{item.projectName}</Text>
          </View>
          <View style={{ width: 20 }}>
            <Image
              style={[styles.iconChecked, { display: item.checked ? 'flex' : 'none' }]}
              source={require('../../images/utils/menu_check.png')}
            />
          </View>
        </View>
      </TouchableOpacity>
    );
  }

  render() {
    let view = null;
    if (this.state.isLoading) {
      view = <CustomLoadingView />;
    } else if (this.state.errorMsg) {
      view = <CustomErrorView errorInfo={this.state.errorMsg} />;
    } else {
      view = (
        <View style={{flex:1}}>
          <SearchBox handler={(searchTxt) => {
            isLoadMore = true;
            this.setState({ searchTxt, pageNo: 1 }, () => this.getList());
          }}
          />
          <FlatList
            style={styles.listView}
            data={this.state.projectList}
            ItemSeparatorComponent={() => <View style={myStyles.lineBorderBottom} />}
            renderItem={this.renderRow.bind(this)}
            ListFooterComponent={() => {
              if (this.state.pageNo) {
                return (// 设置上拉加载布局
                  <View style={styles.loadMore}>
                    <ActivityIndicator
                      style={styles.indicator}
                      size="large"
                      color="red"
                      animating
                    />
                    <Text style={{ textAlign: 'center' }}>正在加载更多</Text>
                  </View>
                );
              }
              return null;
            }}
            onEndReached={this.loadMoreData}
          />
        </View>
      );
    }
    return (
      <View style={styles.container}>
        <View style={styles.paddingView} />
        <View style={styles.popView}>
          <View style={[styles.popTitle, myStyles.flexRowSpaceBetween, myStyles.lineBorderBottom]}>
            <TouchableOpacity onPress={() => this.props.onClose()}>
              <Text style={styles.titleText}>取消</Text>
            </TouchableOpacity>
            <Text style={styles.titleText}>请选择项目</Text>
            <TouchableOpacity onPress={this.onProjectSureClick}>
              <Text style={styles.titleText}>确定</Text>
            </TouchableOpacity>
          </View>
          {view}
        </View>
      </View>
    );
  }
}
const weekDayHeight = (Dimensions.get('window').width - 16) / 7.0 + 71;
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  paddingView: {
    height: weekDayHeight + 8 + 64, // 64 是原生标题栏的高度
    backgroundColor: '#000000',
    opacity: 0.5,
  },
  popView: {
    flex: 1,
    backgroundColor: '#f6f6f6',
  },
  popTitle: {
    height: 48,
    padding: 10,
    backgroundColor: '#ECEDEE',
    borderRadius:8,
  },
  titleText: {
    fontSize: 16,
  },
  listView: {

  },
  listItem: {
    paddingLeft: 16,
    paddingRight: 16,
    backgroundColor: 'white',
  },
  projectInfo: {
    paddingTop: 10,
    paddingBottom: 10,
    flex: 1,
  },
  projectText: {
    fontSize: 14,
    color: '#4A4A4A',
  },
  checkedText: {
    color: '#3295F9',
  },
  iconChecked: {
    width: 20,
  },
});
export default ProjectList;
